<?php
/**
 *
 * 系统设置-学期(服务)
 * Author: chain
 * Date: 2020/12/10 10:12
 */


namespace App\Services\System;


use Illuminate\Support\Facades\Cache;
use App\Models\System\Term;
use App\Models\System\Classroom;

class TermService
{
    /**
     * @var \App\Repositories\System\TeacherRepository $teacherRepository
     */
    private $teacherRepository;

    /**
     * 获取学期列表
     * @author lxy
     * @datetime 2022-04-28
     */
    public function getTermList($request)
    {
        $limit = $request['limit']??10;
        $year = '';

        if (isset($request['search']['title'] )&& !empty($request['search']['title'])){
            $year = $request['search']['title'];
        }

        $result = Term::when($year, function($q) use($year) {
            $q->where('title','like','%'.$year.'%');
        })->orderBy('id','desc')
        ->paginate($limit)
        ->toArray();

        return $result;
    }

    /**
     * 设置学期
     */
    public function setTerm($request)
    {
        $id = !empty($request['id'])?$request['id']:'';
        unset($request['id']);

        // if($request['is_now'] == 1){
        //     Term::where([])->update(['is_now'=>0]);
        // }

        if(!$id){
            $result = Term::create($request);
        }else{
            $result = Term::where('id',$id)->update($request);
        }
        return $result;
    }
    
    /**
     * 获取一条数据
     */
    public function getTermById($request)
    {
        return $result = Term::where('id',$request['id'])->first();
    }

    /**
     * 删除
     */
    public function delTerm($request)
    {
        return $result = Term::where('id',$request['id'])->delete();
    }

    /**
     * 获取学期数据
     * @author lxy
     * @datetime 2022-04-29
     */
    public function getTermData($request)
    {
        $result = Term::orderBy('id','desc')->get()->toArray();
        return $result;
    }

    //*******************外部调用方法****************************************************
    public function updateOrCreateCore($where,$data)
    {
        if(empty($where) || empty($data)){
            return false;
        }
        Term::updateOrCreate($where,$data);
    }

    public function deleteCore($id, $keyName = 'id'){
        if ( $keyName === FALSE ) {
            $where = $id;
        } else {
            $where = [
                $keyName => $id,
            ];
        }
        Term::where($where)->delete();
    }
    

}
